<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { axiosrmedical } from '../../http/axiosRead';

// 定义患者数据接口
interface Patient {
  id: number;
  name: string;
  idCard: string;
  relation: string;
}

const router = useRouter();
const route = useRoute();
const patients = ref<Patient[]>([]);
const loading = ref<boolean>(false);
const fromPage = ref<string>('');

// 获取所有患者信息
const fetchPatients = async () => {
  loading.value = true;
  try {
    const response = await axiosrmedical.get('/Patient/GetPatients', {
      headers: { 'axiosrmedical': true }
    });
    
    if (response.data.code === 200) {
      patients.value = response.data.pageData || [];
    } else {
      console.error('获取患者信息失败:', response.data.msg);
    }
  } catch (error) {
    console.error('请求出错:', error);
  } finally {
    loading.value = false;
  }
};

// 选择患者
const selectPatient = (patientId: number) => {
  if (fromPage.value === 'refund') {
    router.push(`/refund?selectedPatientId=${patientId}`);
  } else {
    // 默认返回退款页面
    router.push(`/refund?selectedPatientId=${patientId}`);
  }
};

onMounted(() => {
  // 获取来源页面
  fromPage.value = route.query.from as string || '';
  
  // 获取患者列表
  fetchPatients();
});
</script>

<template>
  <div class="patient-select-page">
    <div class="header">
      <van-nav-bar
        title="选择患者"
        left-arrow
        @click-left="router.back()"
      />
    </div>

    <div class="content">
      <van-loading v-if="loading" vertical>加载中...</van-loading>
      
      <template v-else>
        <div class="patient-list">
          <van-cell-group inset>
            <van-cell 
              v-for="patient in patients" 
              :key="patient.id"
              :title="patient.name"
              :label="`身份证: ${patient.idCard} | 关系: ${patient.relation}`"
              clickable
              @click="selectPatient(patient.id)"
            >
              <template #right-icon>
                <van-icon name="arrow" color="#969799" />
              </template>
            </van-cell>
          </van-cell-group>
        </div>
        
        <div v-if="patients.length === 0" class="no-data">
          <van-empty description="暂无患者信息" />
        </div>
      </template>
    </div>
  </div>
</template>

<style scoped>
.patient-select-page {
  min-height: 100vh;
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
}

.content {
  flex: 1;
  padding: 16px;
}

.patient-list {
  margin-bottom: 20px;
}

.no-data {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}
</style> 